package com.xiaoshuidi.cloud.module.member.mq.listerner;

import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.systemevent.core.LeaseSystemEventData;
import com.xiaoshuidi.cloud.framework.systemevent.core.LeaseSystemEventListener;
import com.xiaoshuidi.cloud.framework.systemevent.core.LeaseSystemEventTypeEnum;
import com.xiaoshuidi.cloud.framework.systemevent.core.data.LeaseSystemEventBookingCancel;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.CancelBookingCouponSendVO;
import com.xiaoshuidi.cloud.module.member.enums.coupon.CouponTypeEnum;
import com.xiaoshuidi.cloud.module.member.service.coupon.CouponCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;

@Component
@Slf4j
public class LeaseCancelBookingSystemEventListener implements LeaseSystemEventListener {
    @Resource
    private CouponCustomerService couponCustomerService;

    @Resource
    private PlatformTransactionManager transactionManager;

    @Resource
    private TransactionDefinition transactionDefinition;

    @Override
    public LeaseSystemEventTypeEnum getEventType() {
        return LeaseSystemEventTypeEnum.BOOKING_CANCEL;
    }

    @Override
    public void onEvent(LeaseSystemEventData event) {
        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
        LeaseSystemEventBookingCancel data = (LeaseSystemEventBookingCancel) event;
        log.info("收到取消预定消息 {}", JsonUtils.toJsonString(data));

        try {
            CancelBookingCouponSendVO cancelBookingCouponSendVO = new CancelBookingCouponSendVO()
                    .setUserId(data.getUserId())
                    .setApartmentId(data.getApartmentId())
                    .setBusinessKey(CouponTypeEnum.RESERVATION_DISCOUNT.getCode()
                            + data.getBookingId())
                    .setTenantId(data.getTenantId());
            couponCustomerService.cancelBookingCoupon(cancelBookingCouponSendVO);
            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            log.error("预定发券异常");
            transactionManager.rollback(transactionStatus);
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "预定发券异常!");
        }
    }
}
